package com.koicarp.university.graduate.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.koicarp.university.graduate.auth.service.UniversityAuthUser;
import com.koicarp.university.graduate.service.dao.SysRoleDao;
import com.koicarp.university.graduate.service.entity.SysRole;
import com.koicarp.university.graduate.service.vo.userManage.UserRoleVo;
import com.koicarp.university.graudate.common.constant.BaseConstant;
import com.koicarp.university.graudate.common.dao.SysUserDao;
import com.koicarp.university.graudate.common.dto.SysUserDto;
import com.koicarp.university.graduate.auth.service.ISysUserService;
import com.koicarp.university.graudate.common.entity.SysUser;
import com.koicarp.university.graudate.common.utils.UniversityResponse;
import com.koicarp.university.graudate.common.utils.UniversityUtil;
import com.koicarp.university.graudate.common.vo.UserByRoleVo;
import com.koicarp.university.graudate.common.vo.UserPasswordVo;
import com.koicarp.university.graudate.common.vo.UserRelaRoleVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @auther liutao
 * @Date 2020-08-24 17:17:08
 */
@Service("sysUserService")
@Slf4j
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements ISysUserService {

    private final SysUserDao sysUserDao;


    @Autowired
    PasswordEncoder passwordEncoder;
    public SysUserDto getUserByName(String name){
        SysUserDto sysUserDto = sysUserDao.findByUserIdOrTel(name);
        String role = sysUserDto.getRole();
        String[] strRole = role.split(",");
        System.out.println(Arrays.toString(strRole));
        String[] strName = sysUserDto.getRoleName().split(",");
        String[] strRoleId = sysUserDto.getRoleId().split(",");
        sysUserDto.setRoleIds(strRoleId);
        sysUserDto.setRoleNames(strName);
        sysUserDto.setRoles(strRole);
        return sysUserDto;
    }

    @Override
    public UniversityResponse getUserListByRoleWithPage(UserByRoleVo vo) {
        UniversityResponse response = new UniversityResponse();
        Page<SysUser> page = null;
        boolean findOne = UniversityUtil.isNotNull(vo.getUserId());
        boolean isPage = UniversityUtil.isNotNull(vo.getPageNum())
                && UniversityUtil.isNotNull(vo.getPageSize());
        response.code(BaseConstant.RESPONSE_CODE_SUCCESS_200);
        response.message(BaseConstant.RESPONSE_MESSAGE_OPR_SUCCESS);
        if (!findOne && !isPage){
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_PARAM_WRONG);
            return response;
        }
        if (findOne){
            page = new Page<>(1,1,false);
        } else{
            page = new Page<>(vo.getPageNum(),vo.getPageSize(),true);
        }
        IPage<SysUserDto> result = null;
        if (UniversityUtil.isNotNull(vo.getUserName())){
            result = sysUserDao.queryBlurByRoleWithPage(page,vo);
        }else{
            result = sysUserDao.queryByRoleWithPage(page,vo);
        }
        for (SysUserDto s: result.getRecords()) {
            String role = s.getRole();
            String[] strRole = role.split(",");
            if (strRole.length==0){
                continue;
            }
            s.setRoles(strRole);
        }
        if (findOne){
            List<SysUserDto> list = result.getRecords();
            if (list == null || list.size() == 0){
                response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
                response.message(BaseConstant.RESPONSE_MESSAGE_OPR_RESULT_NULL);
                log.info(BaseConstant.RESPONSE_MESSAGE_OPR_RESULT_NULL);
            } else {
                response.code(BaseConstant.RESPONSE_CODE_SUCCESS_200);
                response.message(BaseConstant.RESPONSE_MESSAGE_OPR_SUCCESS);
                response.data(list.get(0));
            }
        } else {
            response.code(BaseConstant.RESPONSE_CODE_SUCCESS_200);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_SUCCESS);
            Map<String, Object> dataTable = UniversityUtil.getDataTable(result);
            response.data(dataTable);
        }
        return response;
    }

    @Override
    public UniversityResponse removeUserOne(SysUser sysUser) {
        UniversityResponse response = new UniversityResponse();
        response.code(BaseConstant.RESPONSE_CODE_SUCCESS_200);
        response.message(BaseConstant.RESPONSE_MESSAGE_OPR_SUCCESS);
        int i = sysUserDao.deleteByUserId(sysUser.getUserId());

        if ( i > 0 ){
            int j = sysUserDao.deleteUserRoleRelaByUserId(sysUser.getUserId());
            if (j < 0){
                response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
                response.message(BaseConstant.COMMON_FAIL_KNOW);
            }
        } else {
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message("删除该用户"+BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }

    @Override
    public UniversityResponse removeUserList(List<String> list) {
        UniversityResponse response = new UniversityResponse();
        response.code(BaseConstant.RESPONSE_CODE_SUCCESS_200);
        response.message(BaseConstant.RESPONSE_MESSAGE_OPR_SUCCESS);

        int i = sysUserDao.removeUserList(list);
        if ( i > 0 ){
            int j = sysUserDao.deleteUserRoleRelaByUserIdList(list);
            if (j < 0){
                response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
                response.message(BaseConstant.COMMON_FAIL_KNOW);
            }
        } else {
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message("批量删除用户"+BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }

    @Override
    public UniversityResponse resetPassword(SysUser sysUser) {
        UniversityResponse response = new UniversityResponse();
        response.code(BaseConstant.RESPONSE_CODE_SUCCESS_200);
        response.message(BaseConstant.RESPONSE_MESSAGE_OPR_SUCCESS);
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        sysUser.setPassword(passwordEncoder.encode("123456"));
        int i = sysUserDao.update(sysUser);
        if (i < 0){
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message("重置密码"+BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }

    @Override
    public UniversityResponse insert(UserRoleVo userRoleVo) {
        UniversityResponse response = new UniversityResponse();
        response.code(BaseConstant.RESPONSE_CODE_SUCCESS_200);
        response.message(BaseConstant.RESPONSE_MESSAGE_OPR_SUCCESS);
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userRoleVo,sysUser);

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserId,sysUser.getUserId());
        Integer countUserId = sysUserDao.selectCount(wrapper);
        if (countUserId > 0){
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message("用户账号已存在!!!");
            return response;
        }
        wrapper.eq(SysUser::getTel,sysUser.getTel());
        Integer countTel = sysUserDao.selectCount(wrapper);
        if (countTel > 0){
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message("用户电话已存在!!!");
            return response;
        }

        sysUser.setStatus(1);
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        sysUser.setPassword(passwordEncoder.encode("123456"));
        int i = sysUserDao.insert(sysUser);
        List<UserRelaRoleVo> list = new ArrayList<>();
        for (String s :userRoleVo.getRoleId()){
            UserRelaRoleVo userRelaRoleVo = new UserRelaRoleVo();
            userRelaRoleVo.setUserId(userRoleVo.getUserId());
            userRelaRoleVo.setRoleId(s);
            list.add(userRelaRoleVo);
        }
        int j = sysUserDao.insertUserRelaRole(list);

        if (i < 0|| j< 0){
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }

    @Override
    public UniversityResponse update(SysUser sysUser) {
        UniversityResponse response = new UniversityResponse();
        response.code(BaseConstant.RESPONSE_CODE_SUCCESS_200);
        response.message(BaseConstant.RESPONSE_MESSAGE_OPR_SUCCESS);

        int i = sysUserDao.update(sysUser);

        if (i < 0){
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
        }
        return response;
    }

    public UniversityResponse updateByUser(UserRoleVo userRoleVo){
        UniversityResponse response = new UniversityResponse();
        response.code(BaseConstant.RESPONSE_CODE_SUCCESS_200);
        response.message(BaseConstant.RESPONSE_MESSAGE_OPR_SUCCESS);

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getTel,userRoleVo.getTel());
        List<SysUser> list = sysUserDao.selectList(wrapper);
        if (list.isEmpty()){
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message("电话号码已存在！");
            return response;
        }
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userRoleVo,user);
        int updateUser = sysUserDao.update(user);
        if (updateUser > 0){
            wrapper.eq(SysUser::getUserId,userRoleVo.getUserId());
            SysUser sysUser= sysUserDao.selectOne(wrapper);
            if (!UniversityUtil.isNotNull(sysUser)){
                response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
                response.message("未知错误！请联系管理员！");
                return response;
            }
            sysUserDao.deleteUserRoleRelaByUserId(sysUser.getUserId());
            List<UserRelaRoleVo> roleVos = new ArrayList<>();
            for (String s :userRoleVo.getRoleId()){
                log.info("角色用户中间表信息配置。。");
                UserRelaRoleVo userRelaRoleVo = new UserRelaRoleVo();
                userRelaRoleVo.setUserId(userRoleVo.getUserId());
                userRelaRoleVo.setRoleId(s);
                roleVos.add(userRelaRoleVo);
            }
            int j = sysUserDao.insertUserRelaRole(roleVos);
            if (j < 0 ){
                response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
                response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
            }
        }
        return response;
    }

    @Override
    public UniversityResponse updatePassword(UserPasswordVo vo) {
        UniversityResponse response = new UniversityResponse();
        UniversityAuthUser universityAuthUser =(UniversityAuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userId = universityAuthUser.getUserId();
        log.info("name:      "+userId);
        response.code(BaseConstant.RESPONSE_CODE_SUCCESS_200);
        response.message(BaseConstant.RESPONSE_MESSAGE_OPR_SUCCESS);
        BCryptPasswordEncoder bcp = new BCryptPasswordEncoder();
        System.out.println(vo.getOldPassword());
        SysUserDto sysUserDto = sysUserDao.findByUserIdOrTel(userId);
        //bcp.matches(mm_pub,mm_encode)，第一个参数是前端传递过来的明文密码，如123456，第二个参数是添加用户时存储的密码
        if(bcp.matches(vo.getOldPassword(),sysUserDto.getPassword())){
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            sysUser.setPassword(bcp.encode(vo.getNewPassword()));
            log.info("验证成功！！！");
            int i = sysUserDao.update(sysUser);
            if ( i < 0){
                response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
                response.message(BaseConstant.RESPONSE_MESSAGE_OPR_FAILED);
            }
        }else{
            log.info("验证失败！！！");
            response.code(BaseConstant.RESPONSE_CODE_FAILED_500);
            response.message(BaseConstant.USER_PASSWORD_ERROR);
        }
        return response;
    }


}
